const Model = require("../../models");
const { cryto, uuid } = require("../../utils");
const { USER_TYPES, DOCTOR_VALID_STATUS } = require("../../sys_config");

module.exports = {
  name: "doctor_info",

  async join(data) {
    try {
      if (!data.length) return { ok: 0, err: "空数据" };
      const model = Model.models.user;
      const _doctors = await model.core.findAll({
        where: { phone: data.map((n) => n.phone) },
      });
      const doctors = data.reduce((res, cur) => {
        if (!_doctors.some((n) => n.phone === cur.phone)) {
          const salt = uuid();
          const password = cryto(cur.password, salt);
          res.push({
            phone: cur.phone,
            password,
            uuid: salt,
            type: USER_TYPES.DOCTOR,
          });
        }
        return res;
      }, []);
      await model.core.bulkCreate(doctors);
      return { ok: 1 };
    } catch (e) {
      console.error(e);
    }
  },

  async get_doctor(query, multi = false) {
    try {
      const res = await Model.models.doctor_info.get_doctors(query);
      return { ok: 1, data: multi ? res : res[0] };
    } catch (e) {
      console.log(e);
      return { ok: 0 };
    }
  },

  async update_info(data) {
    try {
      await Model.models.doctor_info.core.update(data, {
        where: { u_id: data.u_id },
      });
      return { ok: 1 };
    } catch (e) {
      console.log(e);
      return { ok: 0 };
    }
  },

  async update_pb(data) {
    try {
      const res = await Model.models.pb.core.findAll({
        where: { type: [data.pb_time, data.pb_date] },
      });
      const udata = { pb_time_id: res[0].id, pb_date_id: res[1].id };
      await Model.models.doctor_info.core.update(udata, {
        where: { u_id: data.u_id },
      });
      return { ok: 1 };
    } catch (e) {
      console.log(e);
      return { ok: 1 };
    }
  },

  async add_doctor_valid(data) {
    try {
      await Model.models.user.core.update(
        { name: data.name },
        { where: { id: data.u_id } }
      );
      const res = await Model.models.doctor_info.core.create({
        ...data,
        valid: DOCTOR_VALID_STATUS.ONVALID,
      });
      return { ok: 1, data: res };
    } catch (e) {
      console.log(e);
      return { ok: 0 };
    }
  },
};
